'use strict';

const Controller = require('egg').Controller;
const _ = require('lodash');

class SuggApi extends Controller {
  async sugg(ctx) {
    const kw = encodeURI(this.ctx.query.kw);
    if (!kw) {
      ctx.body = [];
      return;
    }
    const redis_key = 'sugg:' + kw;
    const cache_result = await this.service.cacheSvc.get(redis_key);
    if (cache_result != undefined) {
      ctx.body = cache_result;
    } else {
      const response = await ctx.curl(`https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=33639,33744,33273,31254,33691,33855&wd=${kw}&req=2&csor=2&cb=jQuery1102020617794665700417_1617852533550&_=1617852533558`);
      if (response.status == 200) {
        const result = response.data.toString();

        let p = /("q":"[^"]+)/g;
        let r = result.match(p);
        let v = '';
        if (!r) {
          // this.ctx.logger.error(`sugg [${kw}] has no response: [${result}]`);
          ctx.body = [];
          return;
        }
        for (let i = 1; i < r.length; i++) {
          let item = r[i].substr(5);
          v += `<div class=\"acp\" tabindex=\"${i}\">${item}</div>`;
        }
        await this.service.cacheSvc.setex(redis_key, v, 3600 * 24);
        ctx.body = v;
      } else {
        ctx.body = [];
      }
    }
  }
}

module.exports = SuggApi;
